package com.xxx.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxx.course.entity.EduSubject;
import com.xxx.course.entity.subject.ChildrenSubject;
import com.xxx.course.entity.subject.ParentSubject;
import com.xxx.course.mapper.EduSubjectMapper;
import com.xxx.course.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author chn
 * @since 2022-05-29
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public List<ParentSubject> listTree() {
        List<EduSubject> parentList = baseMapper.selectList(new QueryWrapper<EduSubject>().eq("parent_id", 0));
        List<EduSubject> childrenList = baseMapper.selectList(new QueryWrapper<EduSubject>().ne("parent_id", 0));
        //一级分类实体
        List<ParentSubject> parentSubjects=new ArrayList<>();
        for (EduSubject subject : parentList) {
            ParentSubject parentSubject = new ParentSubject();
            BeanUtils.copyProperties(subject,parentSubject);
            parentSubjects.add(parentSubject);
            //二级分类实体
            List<ChildrenSubject> childrenSubjects=new ArrayList<>();
            for (EduSubject childSubject : childrenList) {
                if (childSubject.getParentId().equals(subject.getId())){
                    ChildrenSubject childrenSubject=new ChildrenSubject();
                    BeanUtils.copyProperties(childSubject,childrenSubject);
                    childrenSubjects.add(childrenSubject);
                }
            }
            //加入到children中
            parentSubject.setChildren(childrenSubjects);
        }

        return parentSubjects;
    }

}
